'use strict'

/**
 * 本模块负责维护和微信服务端之间的access_token，该token为我方服务端调用微信服务端的凭证，非与客户端之间的凭证
 * 
 * 微信小程序开发文档：
 * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
 * 
 * 
 */

const jsreq = require('jsreq')
const redis = require('./../db/redis')
const wx_config = require('./../../config/wx')




/**
 * 从微信服务端获取access_token
 * @returns {Promise} resolve(access_token)
 */
async function fetch() {
    return new Promise(function (resolve, reject) {
        jsreq({
            url: 'https://api.weixin.qq.com/cgi-bin/token',
            query: {
                grant_type: 'client_credential',
                appid: wx_config.appid,
                secret: wx_config.secret
            }
        }).then(function (response) {
            const data = JSON.parse(response.data)
            if (!data.errcode) {
                resolve(data.access_token)
            } else {
                reject(data.errmsg)
            }
        })
    })
}

/**
 * 用于外部定时任务，自动刷新Redis中的access_token
 */
async function refresh() {
    const access_token = await fetch()
    redis.set('access_token', access_token)
}


/**
 * 内部函数调用，传递微信服务端的access_token
 */
async function get() {
    return new Promise(async function (resolve, reject) {
        const access_token = await redis.get('access_token')
        if (access_token) {
            resolve(access_token)
        } else {
            await refresh()
            get()
        }
    })
}


module.exports = {
    fetch,
    refresh,
    get
}